const express = require('express');
const multer = require('multer');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, notFound, forbidden, asyncHandler, paginated } = require('../utils/response');
const { authenticateToken } = require('../utils/auth');
const { validatePagination, validateFileType, validateFileSize, validateDate } = require('../utils/validation');

// 导入服务层和DAO层
const dailyService = require('../services/dailyService');
const dailyDao = require('../dao/dailyDao');

// 配置文件上传
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 50 * 1024 * 1024, // 50MB for video
    files: 1
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['mp4', 'mov'];
    const validation = validateFileType(file, allowedTypes);
    if (validation.isValid) {
      cb(null, true);
    } else {
      cb(new Error(validation.message), false);
    }
  }
});

/**
 * 获取每日一句
 * GET /daily/sentence
 */
router.get('/sentence', asyncHandler(async (req, res) => {
  const { date } = req.query;
  let targetDate = new Date();

  // 如果指定了日期，验证并使用指定日期
  if (date) {
    const dateValidation = validateDate(date);
    if (!dateValidation.isValid) {
      return badRequest(res, '日期格式错误: ' + dateValidation.message);
    }
    targetDate = dateValidation.date;
  }

  const sentence = await dailyDao.getTodaySentence(targetDate);
  
  if (!sentence) {
    return notFound(res, '今日句子不存在');
  }

  const formattedSentence = {
    id: sentence.id,
    date: sentence.date,
    chinese: sentence.chinese,
    pinyin: sentence.pinyin,
    english: sentence.english,
    source: sentence.source,
    audioUrl: sentence.audio_url,
    difficulty: sentence.difficulty,
    tags: sentence.tags ? JSON.parse(sentence.tags) : [],
    meaning: sentence.meaning,
    background: sentence.background
  };

  success(res, formattedSentence);
}));

/**
 * 获取历史每日一句
 * GET /daily/sentences
 */
router.get('/sentences', asyncHandler(async (req, res) => {
  const { page, limit } = validatePagination(req.query);
  const { month } = req.query;

  const options = { page, limit };

  // 如果指定了月份，验证并添加到查询条件
  if (month) {
    const monthValidation = validateDate(month, 'YYYY-MM');
    if (!monthValidation.isValid) {
      return badRequest(res, '月份格式错误: ' + monthValidation.message);
    }
    options.month = month;
  }

  const result = await dailyDao.getDailySentences(options);

  const formattedList = result.sentences.map(sentence => ({
    id: sentence.id,
    date: sentence.date,
    chinese: sentence.chinese,
    pinyin: sentence.pinyin,
    english: sentence.english,
    source: sentence.source,
    difficulty: sentence.difficulty,
    tags: sentence.tags ? JSON.parse(sentence.tags) : []
  }));

  paginated(res, formattedList, result.total, page, limit);
}));

/**
 * 提交每日朗读
 * POST /daily/submit
 */
router.post('/submit', authenticateToken, upload.single('videoFile'), asyncHandler(async (req, res) => {
  const { sentenceId, duration } = req.body;
  const videoFile = req.file;
  const userId = req.user.id;

  // 参数验证
  if (!sentenceId || isNaN(parseInt(sentenceId))) {
    return badRequest(res, '无效的句子ID');
  }

  if (!videoFile) {
    return badRequest(res, '请上传视频文件');
  }

  if (!duration || isNaN(parseFloat(duration))) {
    return badRequest(res, '请提供录制时长');
  }

  // 验证文件大小
  const fileSizeValidation = validateFileSize(videoFile, 50 * 1024 * 1024); // 50MB
  if (!fileSizeValidation.isValid) {
    return badRequest(res, fileSizeValidation.message);
  }

  const sentenceIdInt = parseInt(sentenceId);
  const durationFloat = parseFloat(duration);

  // 检查句子是否存在
  const sentence = await dailyDao.getDailySentenceById(sentenceIdInt);
  if (!sentence) {
    return notFound(res, '句子不存在');
  }

  // 检查今天是否已经提交过
  const today = new Date().toISOString().split('T')[0];
  const existingRecord = await dailyDao.getUserTodayRecord(userId, today);
  if (existingRecord) {
    return badRequest(res, '今天已经提交过朗读记录了');
  }

  // TODO: 这里应该调用语音评测服务进行实际的语音分析
  // 现在使用模拟数据
  const mockEvaluationResult = {
    overall_score: Math.floor(Math.random() * 30) + 70, // 70-100分
    pronunciation_score: Math.floor(Math.random() * 30) + 70,
    fluency_score: Math.floor(Math.random() * 30) + 70,
    completeness_score: Math.floor(Math.random() * 30) + 70,
    suggestions: ['语调自然，发音准确', '可以适当增加感情色彩']
  };

  // 保存视频文件 (这里应该保存到文件系统或云存储)
  const videoUrl = `https://example.com/daily/videos/${Date.now()}_${videoFile.originalname}`;

  // 创建朗读记录
  const recordData = {
    user_id: userId,
    sentence_id: sentenceIdInt,
    video_url: videoUrl,
    duration: durationFloat,
    score: mockEvaluationResult.overall_score,
    pronunciation_score: mockEvaluationResult.pronunciation_score,
    fluency_score: mockEvaluationResult.fluency_score,
    completeness_score: mockEvaluationResult.completeness_score,
    suggestions: JSON.stringify(mockEvaluationResult.suggestions),
    practice_date: today
  };

  const readingRecord = await dailyDao.createDailyRecord(recordData);

  // 确定评级
  let level = '需要改进';
  if (mockEvaluationResult.overall_score >= 90) {
    level = '优秀';
  } else if (mockEvaluationResult.overall_score >= 80) {
    level = '良好';
  } else if (mockEvaluationResult.overall_score >= 70) {
    level = '一般';
  }

  const responseData = {
    id: readingRecord.id,
    sentenceId: sentenceIdInt,
    score: mockEvaluationResult.overall_score,
    level,
    accuracy: mockEvaluationResult.pronunciation_score,
    fluency: mockEvaluationResult.fluency_score,
    completeness: mockEvaluationResult.completeness_score,
    videoUrl,
    suggestions: mockEvaluationResult.suggestions,
    createdAt: readingRecord.created_at
  };

  success(res, responseData, '朗读提交成功');
}));

/**
 * 获取朗读历史
 * GET /daily/history
 */
router.get('/history', authenticateToken, asyncHandler(async (req, res) => {
  const { page, limit } = validatePagination(req.query);
  const { month } = req.query;
  const userId = req.user.id;

  const options = { page, limit };

  // 如果指定了月份，验证并添加到查询条件
  if (month) {
    const monthValidation = validateDate(month, 'YYYY-MM');
    if (!monthValidation.isValid) {
      return badRequest(res, '月份格式错误: ' + monthValidation.message);
    }
    options.month = month;
  }

  const result = await dailyDao.getUserDailyRecords(userId, options);

  const formattedList = result.records.map(record => {
    let level = '需要改进';
    if (record.score >= 90) {
      level = '优秀';
    } else if (record.score >= 80) {
      level = '良好';
    } else if (record.score >= 70) {
      level = '一般';
    }

    return {
      id: record.id,
      date: record.practice_date,
      sentence: record.dailySentence ? record.dailySentence.chinese : '未知句子',
      score: record.score,
      level,
      createdAt: record.created_at,
      accuracy: record.pronunciation_score,
      fluency: record.fluency_score,
      completeness: record.completeness_score
    };
  });

  // 获取统计数据
  const statistics = await dailyDao.getUserDailyStats(userId);

  paginated(res, formattedList, result.total, page, limit, { statistics });
}));

/**
 * 获取朗读记录详情
 * GET /daily/history/:id
 */
router.get('/history/:id', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的朗读记录ID');
  }

  const record = await dailyDao.getDailyRecordById(parseInt(id));
  
  if (!record) {
    return notFound(res, '朗读记录不存在');
  }

  // 检查是否为当前用户的记录
  if (record.user_id !== userId) {
    return forbidden(res, '无权访问此朗读记录');
  }

  let level = '需要改进';
  if (record.score >= 90) {
    level = '优秀';
  } else if (record.score >= 80) {
    level = '良好';
  } else if (record.score >= 70) {
    level = '一般';
  }

  const detailData = {
    id: record.id,
    date: record.practice_date,
    sentence: record.dailySentence ? record.dailySentence.chinese : '未知句子',
    pinyin: record.dailySentence ? record.dailySentence.pinyin : '',
    english: record.dailySentence ? record.dailySentence.english : '',
    source: record.dailySentence ? record.dailySentence.source : '',
    score: record.score,
    level,
    accuracy: record.pronunciation_score,
    fluency: record.fluency_score,
    completeness: record.completeness_score,
    duration: record.duration,
    videoUrl: record.video_url,
    suggestions: record.suggestions ? JSON.parse(record.suggestions) : [],
    createdAt: record.created_at
  };

  success(res, detailData);
}));

/**
 * 获取打卡日历
 * GET /daily/calendar
 */
router.get('/calendar', authenticateToken, asyncHandler(async (req, res) => {
  const { year, month } = req.query;
  const userId = req.user.id;

  // 默认为当前年月
  const currentDate = new Date();
  const targetYear = year ? parseInt(year) : currentDate.getFullYear();
  const targetMonth = month ? parseInt(month) : currentDate.getMonth() + 1;

  if (targetYear < 2020 || targetYear > 2030) {
    return badRequest(res, '年份范围应在2020-2030之间');
  }

  if (targetMonth < 1 || targetMonth > 12) {
    return badRequest(res, '月份范围应在1-12之间');
  }

  const calendar = await dailyDao.getUserMonthlyCalendar(userId, targetYear, targetMonth);

  success(res, {
    year: targetYear,
    month: targetMonth,
    calendar,
    summary: {
      totalDays: calendar.length,
      completedDays: calendar.filter(day => day.completed).length,
      averageScore: calendar.length > 0 
        ? (calendar.reduce((sum, day) => sum + (day.score || 0), 0) / calendar.filter(day => day.completed).length).toFixed(1)
        : 0
    }
  });
}));

/**
 * 获取连续打卡统计
 * GET /daily/streak
 */
router.get('/streak', authenticateToken, asyncHandler(async (req, res) => {
  const userId = req.user.id;
  
  const streakData = await dailyDao.getUserStreakData(userId);
  
  success(res, streakData);
}));

/**
 * 获取每日朗读排行榜
 * GET /daily/leaderboard
 */
router.get('/leaderboard', asyncHandler(async (req, res) => {
  const { period = 'month', limit = 10 } = req.query;
  
  // 验证周期参数
  const allowedPeriods = ['week', 'month', 'all'];
  if (!allowedPeriods.includes(period)) {
    return badRequest(res, `统计周期无效，允许的值: ${allowedPeriods.join(', ')}`);
  }

  const leaderboard = await dailyDao.getDailyLeaderboard({
    period,
    limit: parseInt(limit)
  });

  const formattedLeaderboard = leaderboard.map((item, index) => ({
    rank: index + 1,
    userId: item.user_id,
    username: item.user.username,
    nickname: item.user.nickname,
    avatar: item.user.avatar,
    averageScore: parseFloat(item.dataValues.avgScore).toFixed(1),
    practiceCount: parseInt(item.dataValues.practiceCount),
    continuousDays: parseInt(item.dataValues.continuousDays || 0)
  }));

  success(res, formattedLeaderboard);
}));

module.exports = router;
